package ext.tianma.bom.util;

import java.io.PrintWriter;
import java.io.StringWriter;

public class StringUtil {
	/**
	 * @deprecated replace old string with new String
	 * @param text
	 * @param repl
	 * @param with
	 * @return
	 */
	public static String replaceAll(String text, String repl, String with) {
		return replace(text, repl, with, -1);
	}

	/**
	 * replace first old string with new String
	 * 
	 * @param text
	 * @param repl
	 * @param with
	 * @return
	 */
	public static String replaceFirst(String text, String repl, String with) {
		return replace(text, repl, with, 1);
	}

	/**
	 * @deprecated user String.replaceAll()
	 * @param text
	 * @param repl
	 * @param with
	 * @param max
	 * @return
	 */
	public static String replace(String text, String repl, String with, int max) {
		if (text == null || repl == null || repl.length() == 0 || max == 0)
			return text;
		if (with == null)
			with = "";
		StringBuffer buf = new StringBuffer(text.length());
		int start = 0;
		int end = 0;
		do {
			if ((end = text.indexOf(repl, start)) == -1)
				break;
			buf.append(text.substring(start, end)).append(with);
			start = end + repl.length();
		} while (--max != 0);
		buf.append(text.substring(start));
		return buf.toString();
	}

	/**
	 * check the string is null or empty
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNullOrEmpty(String str) {
		return (str == null || "".equals(str) || str.equals("null") || str
				.equals("NULL"));
	}

	/**
	 * check the char is 0--9
	 * 
	 * @param c
	 * @return
	 */
	public static boolean isNumber(char c) {
		return (c == '0' || c == '1' || c == '2' || c == '3' || c == '4'
				|| c == '5' || c == '6' || c == '7' || c == '8' || c == '9');
	}

	public static boolean hasContents(String str) {
		return !isNullOrEmpty(str);
	}

	/**
	 * 字符串是否只包含数字和字母
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isNumberOrChar(String str) {
		return str.matches("[0-9a-zA-Z]*");
	}

	/**
	 * e.printStackTrace()转化为字符串
	 * 
	 * @param Exception
	 *            e
	 * @return String
	 */
	public static String getErrorInfoFromException(Exception e) {
		try {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return "\r\n" + sw.toString() + "\r\n";
		} catch (Exception e2) {
			return "bad getErrorInfoFromException";
		}
	}
	
	/**
	 * 替换掉无效字符
	 * @param str
	 * @return
	 */
	public static String repInvalidChar (String str){
		if (str==null || str.equals("")) {
			return str;
		}
		str = str.replace(":", "").replace("\\", "").replace("/", "").replace("?", "").replace("*", "").replace("[", "").replace("]", "");
		return str;
	}
}
